package com.talben.soudian.util;

import java.io.ByteArrayInputStream;












import org.apache.http.Header;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.talben.soudian.AppContext;
import com.talben.soudian.R;
import com.talben.soudian.TDevice;
import com.talben.soudian.api.SouDianAPI;
import com.talben.soudian.api.UrlConnect;
import com.talben.soudian.ui.UIHelper;
import com.talben.soudian.ui.dialog.CommonDialog;
import com.talben.soudian.ui.dialog.DialogHelper;
import com.talben.soudian.ui.dialog.WaitDialog;

/**
 * 更新管理类
 * 
 * @author FireAnt（http://my.oschina.net/LittleDY）
 * @version 创建时间：2014年11月18日 下午4:21:00
 * 
 */

public class UpdateManager {

	private Context mContext;
	
	private boolean isShow = false;
	
	private WaitDialog _waitDialog;
	
	private Integer serverVersion;
	
	private String appName;
	
	private String UpdateUrl;

	private AsyncHttpResponseHandler mCheckUpdateHandle = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			hideCheckDialog();
			if (isShow) {
				showFaileDialog();
			}
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			hideCheckDialog();
			try {
				String result = new String(arg2, "utf-8");
				JSONObject jObj = new JSONObject(result);
				appName = jObj.getString("info");
				serverVersion = jObj.getInt("version");
				UpdateUrl = UrlConnect.HOST + jObj.getString("apkLink");
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			
			onFinshCheck();
		}
	};

	public UpdateManager(Context context, boolean isShow) {
		this.mContext = context;
		this.isShow = isShow;
	}
	
	public boolean haveNew() {
		if (serverVersion == null) {
			return false;
		}
		boolean haveNew = false;
		int curVersionCode = TDevice.getVersionCode(AppContext
				.getInstance().getPackageName());
		if (curVersionCode < serverVersion) {
			haveNew = true;
		}
		return haveNew;
	}

	public void checkUpdate() {
		if (isShow) {
			showCheckDialog();
		}
		SouDianAPI.checkUpdate(mCheckUpdateHandle);
	}
	
	private void onFinshCheck() {
		if (haveNew()) {
			showUpdateInfo();
		} else {
			if (isShow) {
				showLatestDialog();
			}
		}
	}

	private void showCheckDialog() {
		if (_waitDialog == null) {
			_waitDialog = DialogHelper.getWaitDialog((Activity) mContext, "正在获取新版本信息...");
		}
		_waitDialog.show();
	}

	private void hideCheckDialog() {
		if (_waitDialog != null) {
			_waitDialog.dismiss();
		}
	}
	
	private void showUpdateInfo() {
		if (serverVersion == null) {
			return;
		}
		CommonDialog dialog = DialogHelper.getPinterestDialogCancelable(mContext);
		dialog.setTitle("发现新版本");
		dialog.setMessage(appName);
		dialog.setNegativeButton(R.string.cancel, null);
		dialog.setPositiveButton("更新版本", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				UIHelper.openDownLoadService(mContext, UpdateUrl, appName);
				dialog.dismiss();
			}
		});
		dialog.show();
	}
	
	private void showLatestDialog() {
		CommonDialog dialog = DialogHelper.getPinterestDialogCancelable(mContext);
		dialog.setMessage("已经是最新版本了");
		dialog.setPositiveButton("", null);
		dialog.show();
	}
	
	private void showFaileDialog() {
		CommonDialog dialog = DialogHelper.getPinterestDialogCancelable(mContext);
		dialog.setMessage("网络异常，无法获取新版本信息");
		dialog.setPositiveButton("", null);
		dialog.show();
	}
}
